/*
 * LongInteger class represents a signed integer restricted to 32-bit
 * LongInteger is doubleword compatible
 * */

package cpu.datatypes;

public class LongInteger extends DoubleWord {
	private boolean signed = true;
	
	// Default Constructor
	public LongInteger( ) {
		super( );
	}
	// Copy Constructor
	public LongInteger( LongInteger l ) {
		super( l );
	}
	public LongInteger( int n ) {
		super( );
		fromJavaInt( n );
	}
	
	public int toJavaInt( ) {
		int accumulator = 0;
		if( signed ) {
			for( int i = 0; i < 16; i++ ) {
				if( wordLow.bit( i ).value )
					accumulator += java.lang.Math.pow( 2, i );
			}
			for( int i = 1; i < 16; i++ ) {
				if( wordHigh.bit( i ).value )
					accumulator += java.lang.Math.pow( 2, i - 1 + 16 );
			}
			
			if( wordHigh.bit( 0 ).value ) accumulator = -accumulator;
		}
		return accumulator;
	}
	public boolean fromJavaInt( int value ) {
		// note return value is overflow
		int accumulator = value;
		
		if( signed ) {
			if( value < 0 ) {
				accumulator = -accumulator;
				wordHigh.bit( 0 ).value = true;				
			} else {
				wordHigh.bit( 0 ).value = false;
			}
			
			for( int i = 15; i >= 1; i-- ) {
				if( accumulator / java.lang.Math.pow( 2, i - 1 + 16 ) >= 1 ) {
					wordHigh.bit( i ).value = true;
					accumulator -= java.lang.Math.pow( 2, i - 1 + 16 );
				} else {
					wordHigh.bit( i ).value = false;
				}
			}
			for( int i = 15; i >= 0; i-- ) {
				if( accumulator / java.lang.Math.pow( 2, i ) >= 1 ) {
					wordLow.bit( i ).value = true;
					accumulator -= java.lang.Math.pow( 2, i );
				} else {
					wordLow.bit( i ).value = false;
				}
			}
		}
		if( accumulator != 0 ) 
			return true;		// overflow
		return false;			// no overflow			
	}
}
